package jmine.tec.database.query.columns;

import java.sql.ResultSet;
import java.sql.SQLException;

import jmine.tec.database.query.Column;
import jmine.tec.database.query.Database;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Classe base para implementações de colunas.
 * 
 * @author lundberg
 */
public abstract class AbstractColumn implements Column {

    private static final Log LOG = LogFactory.getLog(Database.class);

    private final int type;

    private final String name;

    /**
     * Construtor
     * 
     * @param type type
     * @param name name
     */
    public AbstractColumn(int type, String name) {
        this.type = type;
        this.name = name;
    }

    /**
     * Método padrão de leitura. Dificilmente adequado, sempre sobrescreva, apenas chame como fallback em caso de erro.
     * 
     * @param rs rs
     * @return string
     */
    public String read(ResultSet rs) {
        try {
            return String.valueOf(rs.getObject(this.getName()));
        } catch (SQLException e) {
            LOG.error(e);
            return "";
        }
    }

    /**
     * {@inheritDoc}
     */
    public String getName() {
        return this.name;
    }

    /**
     * @return type
     */
    protected int getType() {
        return this.type;
    }

    /**
     * {@inheritDoc}
     */
    public boolean supportsFilters() {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return String.format("Column:%s,%s", this.name, this.type);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof AbstractColumn)) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        AbstractColumn o = (AbstractColumn) obj;
        return this.name.equals(o.name);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        return this.name.hashCode();
    }
}
